#include "database_manager.h"

Database_manager::Database_manager(QString sql_type, QString host,
                                   int port, QString user,
                                   QString password, QString db_name,
                                   QObject *parent) :
    QObject(parent)
{
    db = QSqlDatabase::addDatabase(sql_type);
    db.setHostName(host);
    db.setPort(port);
    db.setUserName(user);
    db.setPassword(password);
    db.setDatabaseName(db_name);
    db.open();
}

bool Database_manager::test_connection(QString & out)
{
    bool result = false;
    if (db.isOpen())
    {
        out = "Connection established !";
        result = true;
    }
    else
    {
        out = "Connection refused !";
        //out += db.lastError().databaseText();
        //out += "\n\nDrivers available : " + db.drivers().join(", ");
    }

    return result;
}

bool Database_manager::connection()
{
    return db.open();
}

void Database_manager::disconnection()
{
    db.close();
}

bool Database_manager::insert(QString table)
{
    return true;
}

bool Database_manager::update(QString table)
{
    return true;
}

bool Database_manager::remove(QString table)
{
    return true;
}

int Database_manager::select(QString & out, QString table, bool sort, QString sort_column, QString sort_type)
{
    QSqlQuery query("SELECT * FROM " + table);
    QSqlRecord rec = query.record();

    //int nb_col = rec.count();

    int data_col = rec.indexOf("data");
    int size = 0;

    while (query.next())
    {
        size++;
        out = query.value(data_col).toString();
    }

    return size;
}

bool Database_manager::request(QString q, QList< QHash<QString, QString> > * list_result)
{
    bool result = false;

    QSqlQuery query;
    if (query.prepare(q))
    {
        if ( query.exec() )
        {
            result = true;
            if (list_result)
            {
                QSqlRecord rec = query.record();
                int nb_col = rec.count();
                while (query.next())
                {
                    QHash<QString, QString> dico;
                    for ( int i = 0 ; i < nb_col ; i++ )
                    {
                        dico[rec.fieldName(i)] = query.value(i).toString();
                    }

                    list_result->push_back(dico);
                }
            }
        }
    }

    return result;
}

Database_manager::~Database_manager()
{
    db.close();
    QSqlDatabase::removeDatabase(db.databaseName());
}
